# src/backend/backend_adapter.py
"""
后端适配器 - 整合现有DQN代码的统一接口
"""
import threading
import time
import numpy as np
from typing import Dict, Any, Optional

class BackendAdapter:
    def __init__(self):
        # 游戏状态（简化版）
        self.episode = 0
        self.round = 0
        self.score = 0
        self.player_hp = 100
        self.player_pos = {"x": 8, "y": 8}
        self.game_over = False

        # 训练状态
        self.is_training = False
        self.training_thread = None
        self.ai_control = True

        # 简单地图（17x17）
        self.map_data = self._generate_simple_map()
        self.enemies = []
        self.treasures = []
        self.traps = []

        print("后端适配器初始化完成（简化版）")

    def _generate_simple_map(self):
        """生成简单地图"""
        map_data = [[0 for _ in range(17)] for _ in range(17)]

        # 边界墙壁
        for i in range(17):
            map_data[0][i] = 1
            map_data[16][i] = 1
            map_data[i][0] = 1
            map_data[i][16] = 1

        return map_data

    def get_game_state(self) -> Dict[str, Any]:
        """获取游戏状态"""
        return {
            "map": self.map_data,
            "player": {
                "x": self.player_pos["x"],
                "y": self.player_pos["y"],
                "hp": self.player_hp,
                "max_hp": 100,
                "score": self.score
            },
            "enemies": self.enemies,
            "traps": self.traps,
            "treasures": self.treasures,
            "round": self.round,
            "score": self.score,
            "episode": self.episode,
            "game_over": self.game_over
        }

    def reset_game(self) -> Dict[str, Any]:
        """重置游戏"""
        self.episode += 1
        self.round = 0
        self.score = 0
        self.player_hp = 100
        self.player_pos = {"x": 8, "y": 8}
        self.game_over = False

        # 重新生成简单元素
        self.enemies = [{"x": 5, "y": 5, "hp": 50, "type": "skeleton"}]
        self.treasures = [{"x": 10, "y": 10, "value": 100, "collected": False}]
        self.traps = [{"x": 6, "y": 6, "damage": 10, "triggered": False}]

        return self.get_game_state()

    def execute_action(self, action: int) -> Dict[str, Any]:
        """执行动作"""
        # 动作映射: 0=右, 1=下, 2=左, 3=上
        directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
        if 0 <= action < len(directions):
            dx, dy = directions[action]
            new_x = self.player_pos["x"] + dx
            new_y = self.player_pos["y"] + dy

            # 边界检查
            if 1 <= new_x <= 15 and 1 <= new_y <= 15:
                if self.map_data[new_y][new_x] == 0:
                    self.player_pos["x"] = new_x
                    self.player_pos["y"] = new_y
                    self.round += 1

        reward = 0.1  # 简单奖励
        done = self.round > 100 or self.player_hp <= 0

        return {
            "state": self.get_game_state(),
            "reward": reward,
            "done": done
        }

    def set_ai_control(self, enabled: bool):
        """设置AI控制"""
        self.ai_control = enabled

    def start_training(self, params: Dict[str, Any]):
        """开始训练"""
        self.is_training = True
        self.training_thread = threading.Thread(target=self._training_loop, daemon=True)
        self.training_thread.start()

    def stop_training(self):
        """停止训练"""
        self.is_training = False

    def _training_loop(self):
        """训练循环"""
        while self.is_training:
            if self.ai_control:
                # 简单AI：随机动作
                action = np.random.randint(0, 4)
                self.execute_action(action)

                if self.game_over:
                    self.reset_game()

            time.sleep(0.1)  # 控制训练速度

    def save_model(self, name: str) -> str:
        """保存模型"""
        path = f"checkpoints/{name}.pth"
        print(f"模型保存到: {path}")
        return path

    def load_model(self, path: str):
        """加载模型"""
        print(f"模型加载自: {path}")

    def get_training_stats(self) -> Dict[str, Any]:
        """获取训练统计"""
        return {
            "episode": self.episode,
            "round": self.round,
            "score": self.score,
            "health": self.player_hp,
            "epsilon": 0.1,
            "avg_reward": 0.5,
            "loss": 0.01
        }